package com._bytecode.__javassist;

import javassist.*;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: huangya
 * @Date: 2019/3/30
 * @Description:
 */
public class ObjectUpdate {

    public static void main(String[] args) throws NotFoundException, CannotCompileException,
            IOException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
        ClassPool classPool = ClassPool.getDefault();
        CtClass ctClass = classPool.get("com.hy.classloader_demo.__javassist.User");
//        CtMethod ctMethod = new CtMethod(CtClass.voidType, "showName", new CtClass[]{classPool.get("java.lang.String")}, ctClass);
//        ctMethod.setBody("{System.out.println(\"user name:\" + $1);}");
        CtMethod ctMethod = CtMethod.make("public void showName(String uname){System.out.println(\"user name:\" + uname);}", ctClass);
        ctClass.addMethod(ctMethod);
        ctClass.writeFile("D:\\idea_workspace_demos\\classloader_demo\\src\\main\\java");

        Class clazz = ctClass.toClass();
        Object obj = clazz.newInstance();
        Method method = clazz.getDeclaredMethod("showName", String.class);
        method.invoke(obj, "uname test");
    }

//    public void showName(String uname){System.out.println("user name:" + uname);}

}
